<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 面板1 -->
          <el-tab-pane label="角色管理" name="roles">
            <!-- 新增数据角色按钮 -->
            <el-button type="primary" size="mini" @click="showDialog = true"> <i class="el-icon-plus" /> 新增角色</el-button>
            <!-- 数据表哥 -->
            <!-- data表哥的数据源 -->
            <el-table v-loading="loading" class="myTable" :data="list" border stripe>
              <el-table-column
                label="序号"
                width="100px"
                type="index"
                :index="indexMethods"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button type="success" size="mini" @click="showDialogPre(row.id)">分配权限</el-button>
                  <el-button type="primary" size="mini" @click="editRole(row.id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination

              :current-page="page"
              :page-sizes="[1,2,3,4]"
              :page-size="pagesize "
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <!-- 面板2 -->
          <el-tab-pane label="公司信息" name="company">
            <el-alert
              title="消息提示的文案"
              type="info"
              show-icon
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!--  新增角色按钮 -->
      <el-dialog :title="title" :visible="showDialog">
        <el-form ref="formRef" :rules="rules" :model="form">
          <el-form-item prop="name" label="角色名称" label-width="80px">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item prop="description" label="描述信息" label-width="80px">
            <el-input v-model="form.description" placeholder="请输入角色名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="{ label: 'name' }"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickSubmitPer">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetPoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { reqGetPermissionList } from '@/api/permission.js'
import { mapState } from 'vuex'
import { transfromDepartments } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'roles',
      page: 1,
      pagesize: 3,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      showAssignDialog: false, // 控制弹层的显示隐藏
      treeData: [],
      roleId: '',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入描述信息', trigger: ['blur', 'change'] }
        ]
      },
      companyInfo: {}
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    title() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetPoleList(this.page, this.pagesize)
      this.list = rows
      this.total = total
      this.loading = false
    },
    // 每页条数发生变化的时候触发的方法 可以拿到最新的每页条数
    handleSizeChange(newSize) {
      console.log(newSize)
      this.pagesize = newSize
      this.getRoleList()
    },
    // 页码发生变化的时候触发的方法 可以拿到最新的码
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.page = newPage
      this.getRoleList()
    },
    // 自定义索引列
    indexMethods(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    async del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      }).then(async() => {
        const { message } = await reqDeleteRole(id)
        this.$message.success(message)
        if (this.list.length === 0 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    closeDialog() {
      this.showDialog = false
      this.form = {
        name: '',
        description: ''
      }
      // this.$refs.formRef.resetFields()
    },
    // 角色添加
    clickSubmit() {
      // 预校验
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          const { message } = await reqUpdateRole(this.form)
          // console.log(res)
          this.$message.success(message)
          this.closeDialog()
          this.getRoleList()
        } else {
          const { message } = await reqAddRole(this.form)
          this.$message.success(message)
          this.getRoleList()
          this.closeDialog()
        }
      })
    },
    async editRole(id) {
      console.log(id)
      this.showDialog = true
      const { data } = await reqGetRoleDetail(id)
      // console.log(res)
      this.form = data
    },
    handleClick(tab, event) {
      console.log(tab, event)
      if (tab.name === 'company') {
        this.getCompanyInfo()
      }
    },
    async getCompanyInfo() {
      console.log(this.userInfo)
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyInfo = data
      console.log(this.companyInfo)
    },
    // 点击分配权限方法
    async showDialogPre(id) {
      this.showAssignDialog = true
      const { data } = await reqGetPermissionList()
      this.treeData = transfromDepartments(data, '0')
      const { data: { permIds }} = await reqGetRoleDetail(id)
      this.$refs.treeRef.setCheckedKeys(permIds)
      this.roleId = id
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async clickSubmitPer() {
      console.log(this.$refs.treeRef.getCheckedKeys())
      const { message } = await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success(message)
      this.closeAssignDialog()
    }
  }
}
</script>

<style lang = 'scss' scooped>
.myTable{
   margin-top: 30px;
}
</style>

